package main.implementation;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

import main.api.exception.ResponseException;
import main.implementation.lecoeur.LeCoeurAPI;

public class MultiThreadClient {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {

		class ClientThread extends Thread {
			
			public ClientThread(String threadName){
				super();
			}
			
			public void run(){
				
				int min = 1;
				int max = 12;
				int index;
				
				FileWriter fileWriter;
				BufferedWriter bufferWriter;
				DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM );
				File file = new File("performance_test.txt");

			
				try {
					if(!file.exists()) file.createNewFile();
					Date start = new Date();
					fileWriter = new FileWriter(file.getName(),true);
					bufferWriter = new BufferedWriter(fileWriter);
					bufferWriter.write(getName() + " - Start: " + dateFormat.format(start));
			        bufferWriter.newLine();
					bufferWriter.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				for (int i = 1; i <= 100; i++) {
					index = min + (int) (Math.random() * ((max - min) + 1));
					
					LeCoeurAPI leCoeurAPI = new LeCoeurAPI();
					try {
						leCoeurAPI.getIndexAddress(index);
					} catch (KeyManagementException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (UnknownHostException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (NoSuchAlgorithmException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (URISyntaxException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ResponseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				try {
					Date end = new Date();
					fileWriter = new FileWriter(file.getName(),true);
					bufferWriter = new BufferedWriter(fileWriter);
					bufferWriter.write(getName() + " - End: " + dateFormat.format(end));
					bufferWriter.newLine();
			        bufferWriter.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
		
		for (int i = 1; i <= 100; i++) {
			new ClientThread("Thread" + i).start();
		}

	}

}